package com.mworld.galaxy.bull.web.account;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mworld.galaxy.base.service.account.ShiroDbRealm.ShiroUser;
import com.mworld.galaxy.base.shiro.authc.UsernamePasswordRolesToken;

/**
 * member用户的ajax登录。
 */
@Controller
@RequestMapping(value = "/member")
public class MemberAjaxLoginController {
	private static final int ERR_CODE_LOGIN_FAILED = 100001;
	private static final int ERR_CODE_ACCOUNT_LOCKED = 100002;
	private static final int ERR_CODE_AUTHENTICATED = 100003;

	private static final String REQUIRED_ROLES = "member";

	private static final Logger logger = LoggerFactory.getLogger(MemberAjaxLoginController.class);

    @RequestMapping(value = "ajax-login")
    @ResponseBody
    public Object doLogin(@RequestParam String username, @RequestParam String password,
            @RequestParam(value = "rememberMe", defaultValue = "false") boolean rememberMe,
            HttpServletRequest request) {
    	int err = 0;
        Subject currentUser = SecurityUtils.getSubject();
        if (!currentUser.isAuthenticated()) {
        	UsernamePasswordRolesToken token = new UsernamePasswordRolesToken(username, password, rememberMe, request.getRemoteHost(), REQUIRED_ROLES);
            try {
                currentUser.login(token);
            } catch (UnknownAccountException ex) {
            	err = ERR_CODE_LOGIN_FAILED;
                logger.debug("用户名错误：[username=" + username + "]", ex);
            } catch (IncorrectCredentialsException ex) {
            	err = ERR_CODE_LOGIN_FAILED;
                logger.debug("密码错误。[username=" + username + "]", ex);
            } catch (LockedAccountException ex) {
            	err = ERR_CODE_ACCOUNT_LOCKED;
                logger.debug("当前帐户已锁定。[username=" + username + "]", ex);
            } catch (AuthenticationException ex) {
            	err = ERR_CODE_AUTHENTICATED;
                logger.debug("未授权。[username=" + username + "]", ex);
            }
        }

        // 返回json数据
        ShiroUser principal = (ShiroUser) currentUser.getPrincipal();
        return err == 0 ? "{ \"name\": \"" + principal.getName() + "\" }" : "{ \"err\": " + err + "}";
    }
}
